import 'dart:async';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yyshort/common/apis/user_api.dart';
import 'package:yyshort/common/model/user.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/common/routers/routes.dart';
import 'package:get/get.dart';
import 'package:app_links/app_links.dart';
import 'package:yyshort/pages/ali_player/short_video/short_video_page.dart';
import 'package:yyshort/pages/personal/personal/controller.dart';

import 'index.dart';

class ApplicationController extends GetxController {
  ApplicationController();

  /// 响应式成员变量
  final state = ApplicationState();

  /// 成员变量
  // tab 页标题
  late final List<String> tabTitles;

  // 页控制器
  late PageController pageController;

  // 底部导航项目
  late final List<BottomNavigationBarItem> bottomTabs;

  // tab栏动画
  // void handleNavBarTap(int index) {
  //   print("Tapped nav bar: $index");
  //   if (_isPageControllerInitialized) {
  //     pageController.animateToPage(
  //       index,
  //       duration: const Duration(milliseconds: 200),
  //       curve: Curves.ease,
  //     );
  //   }
  // }
  // 修改后
  void handleNavBarTap(int index) {
    if (_isPageControllerInitialized) {
      if (index == 2) {
        PersonalController controller = Get.find<PersonalController>();
        controller.fetchUserInfo();
      }
      // 使用jumpToPage实现无动画切换
      pageController.jumpToPage(index);
      state.page = index;
      update();
    }
  }

  // tab栏页码切换
  void handlePageChanged(int page) {
    // state.page = page;
  }

  /// 检查pageController是否已初始化
  bool get _isPageControllerInitialized {
    try {
      return pageController.hasClients;
    } catch (_) {
      return false;
    }
  }

  /// scheme 内部打开
  bool isInitialUriIsHandled = false;
  StreamSubscription? uriSub;

  // 第一次打开
  Future<void> handleInitialUri() async {
    if (!isInitialUriIsHandled) {
      isInitialUriIsHandled = true;
      try {
        final uri = await AppLinks().getInitialLink();
        if (uri == null) {
          print('no initial uri');
        } else {
          print('got initial uri: $uri');
        }
      } on PlatformException {
        print('falied to get initial uri');
      } on FormatException catch (err) {
        print('malformed initial uri, ' + err.toString());
      }
    }
  }

  // 程序打开时介入
  void handleIncomingLinks() {
    if (!kIsWeb) {
      uriSub = AppLinks().uriLinkStream.listen(
        (Uri? uri) {
          print('got uri: $uri');

          if (uri != null && uri.path == '/notify/category') {
            Get.toNamed(AppRoutes.Category);
          }
          if (uri != null && uri.path == '/video/player') {
            // 获取id参数
            String? dramaId = uri.queryParameters['id'];

            if (dramaId != null) {
              VideoModel tempModel = VideoModel(id: int.parse(dramaId));
              Get.to(
                () => ShortVideoPage(
                  preload: false,
                  isforyouPage: false,
                  superModel: tempModel,
                ),
              );
            }
          }
        },
        onError: (Object err) {
          print('got err: $err');
        },
      );
    }
  }

  /// 生命周期
  @override
  Future<void> onInit() async {
    super.onInit();

    try {
      // 优先初始化关键组件
      pageController = PageController(initialPage: state.page);

      // 初始化底部导航和标题（确保一定会执行）

      // tabTitles = ['Welcome', 'Cagegory', 'Bookmarks'];

      handleInitialUri();
      handleIncomingLinks();
    } catch (e) {
      print('初始化错误: $e');
      // 即使其他操作失败，也要确保关键UI组件已初始化
      // if (!_isPageControllerInitialized) {
      //   pageController = PageController(initialPage: 0);
      // }
      // 确保bottomTabs被初始化
      // if (!_isBottomTabsInitialized) {
      //   bottomTabs = _initBottomTabs();
      // }
      // 确保tabTitles被初始化
      // if (!_isTabTitlesInitialized) {
      //   tabTitles = ['Welcome', 'Cagegory', 'Bookmarks'];
      // }
    }
  }

  // 检查bottomTabs是否已初始化
  bool get _isBottomTabsInitialized {
    try {
      return bottomTabs.isNotEmpty;
    } catch (_) {
      return false;
    }
  }

  // 检查tabTitles是否已初始化
  bool get _isTabTitlesInitialized {
    try {
      return tabTitles.isNotEmpty;
    } catch (_) {
      return false;
    }
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void dispose() {
    uriSub?.cancel();
    if (_isPageControllerInitialized) {
      pageController.dispose();
    }
    super.dispose();
  }
}
